<?php

require_once 'Column.php';
require_once 'ConnectionStrategy.php';
include_once 'DBConfig.php';
require_once 'Tree.php';

/** Queries to be launched depending on the database engine */
define('SHOWTABLES', 'show tables');
define('GETCOLUMNS', 'show columns from ');
define('GETALLROWS', 'select * from ');

/**
 * Concrete strategy for database connection.
 * @author Daniel Rivera
 */
class MySQLConnection implements ConnectionStrategy {
	
	var $dbConn;
	var $tree;
	var $tables;
	
	/**
	 * Connect to the database
	 */
	public function connect() {
		if (is_null($dbConn)) {
			$this->dbConn = mysql_connect(HOST,USERDB,PASSDB) or die('problemas de conexion');
			mysql_select_db(DBNAME);
		}
	}
	
	/**
	 * Method to create an array with name of tables
	 */
	public function getTables() {
		//we're preparing to dump the database.
		$res = mysql_query(SHOWTABLES);
		$this->tables = array(); //in the first place, obtain the name of each table.
		$tables = array();
		while ($row = mysql_fetch_row($res)) {
			$r = $row[0];
			array_push($tables,$r);
		}
		$this->tables = $tables;
		return $this->tables;
	}
	
	/**
	 * Method used for obtaining the name and type of each column for an specific table
	 * @param tablename Name of the table to obtain the columns for
	 * @return array of Columns objects
	 */
	public function getColumns($tablename) {
		$sql = '' . GETCOLUMNS . $tablename;
		$res = mysql_query($sql);
		if (!$res) {
			die('Can\'t obtain columns');
		}
		$columns = array();
		while ($row = mysql_fetch_row($res)) {
			$myColumn = new Column();
			$myColumn ->columnname = $row[0];
			$myColumn ->columntype = $row[1];
			$myColumn ->columnkey = ($row[3] == 'PRI');
			array_push($columns, $myColumn);
		}
		return $columns;
	}
	
	/**
	 * Use this method to obtain every data in an specific table of the database.
	 * @param tablename Name of the table
	 */
	public function getRowsFromTable($tablename) {
		$sql = GETALLROWS.$tablename;
		echo $sql;
		$res = mysql_query($sql);
		echo $res;
		$elements = array();
		$rstring = '';
		//if ($res) {
			while ($row = mysql_fetch_array($res)) {
				for ($i = 0; $i < sizeof($row);$i++) {
					$e = $row[$i];
					$rstring .= $e;
					if ($i < sizeof($row) - 1) 
						$rstring += ',';
				}
				echo 'element -> '.$elements.'</br>';	
				array_push($elements,$rstring);
				
			}
		//}
		
		return $elements;
	}
	
	/**
	 * Launch this method to generate the database tree.
	 */
	public function obtainData() {
		try {
			$this ->getTables();
			//Now we have the name of the tables in an array
			if (is_null($this->tree)) $this->tree = new Tree();
			//for each table, add it to the database tree
			for ($i=0; $i < len($this->tables); $i++) { 
				$tree->addTable($this->tables[i], $this->getRowsFromTable($tablename));
			}
		} catch (exception $e) {
			
		}
	}
	
}

?>
